package cn.com.callback

import cn.com.callback.ServiceBackInvoke
import cn.com.elite.EliteBean
import groovy.json.*
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import sun.misc.BASE64Encoder

import javax.crypto.BadPaddingException
import javax.crypto.IllegalBlockSizeException
import javax.crypto.NoSuchPaddingException
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.security.InvalidAlgorithmParameterException
import java.security.InvalidKeyException
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException

/**
 *
 * @Title: EncryptUtil* AES加密
 * @author: cosson* @date 2020-03-31 21:28:00
 *
 */
public class apiBPISToKenWO implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiBPISToKenWO.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) throws NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
        long startTime = System.currentTimeMillis();
        response.setCharacterEncoding("UTF-8");
        request.setCharacterEncoding("utf-8");
        String reJson = null;
        long endTime = 0;
        //获取参数aes_str,需加密的字符串
        def type = request.getParameter("aes_str");

        // 密匙
        def KEY = request.getParameter("aeskey");
        // 偏移量
        def OFFSET = request.getParameter("aesiv");
        // 编码
        def sToken = request.getParameter("sToken");
        //获取账号
        log.debug("sToken:" + sToken);
        //获取密码
        def ENCODING = "UTF-8";
        //算法
        def ALGORITHM = "AES";
        // 默认的加密算法
        def CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
        String tokenId = "";
        def dsftokresult = "";
        try {
            if (request.getParameter("sToken") == null) {
                endTime = System.currentTimeMillis();
                reJson = "{\"resultcode\":\"1\",\"resultmessage\":\"处理失败(参数输入异常),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
                return reJson;
            }
            if (sToken != "" && sToken != null) {
                dsftokresult = eliteBean.chaxun_sql("select PARAMETERVALUE from SYSC_PARAMETER where PARAMETER_ID = 'DSFTOK' and MODIFIEDDATE>dateadd(HOUR,-2,GETDATE()) and PARAMETERVALUE='" + sToken + "'", "dataSource");
                if (dsftokresult.size() == 0) {
                    endTime = System.currentTimeMillis();
                    log.warn(dsftokresult.toString());
                    reJson = "{\"resultcode\":\"1\",\"resultmessage\":\"token已失效,请重新登录,调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
                    return reJson;
                } else {
                    // 包装拼接返回JSONObject
                    endTime = System.currentTimeMillis();
                    reJson = "{\"resultcode\":\"0\",\"resultmessage\":\"token未失效,处理完成、调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"token\":\"" + dsftokresult.get(0).get("PARAMETERVALUE") + "\"}";
                    return reJson;
                }
            } else {
                endTime = System.currentTimeMillis();
                reJson = "{\"resultcode\":\"2\",\"resultmessage\":\"处理失败(sToken异常),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
                return reJson;
            }
        } catch (Exception e) {
            log.error("接口处理异常" + e.getMessage());
            // 失败返回
            reJson = "{\"resultcode\":\"4\",\"resultmessage\":\"处理失败(" + e.getMessage() + ")\",\"data\":[]}";

        }
        return reJson;


    }

    //生成token令牌
    public static String makeToken() {
        String token = (System.currentTimeMillis() + new Random().nextInt(999999999)) + "";
        try {
            MessageDigest md = MessageDigest.getInstance("md5");
            byte[] md5 = md.digest(token.getBytes());
            BASE64Encoder encoder = new BASE64Encoder();
            return encoder.encode(md5);
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
}